export const useDeepSeek = () => {
    const sendMessage = async (
      messages: any,
      onChunkReceived: (data: {
        content?: string;
        isThinking?: boolean;
        isAnswer?: boolean;
        error?: string;
        finished?: boolean;
      }) => void
    ) => {
      try {
        const response = await fetch(
          `${import.meta.env.VITE_API_SERVER}/api/chat-stream`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              messages,
              model: "deepseek-chat",
            }),
          }
        );
  
        if (!response.ok) {
          throw new Error(`网络错误: ${response.status} ${response.statusText}`);
        }
  
        const reader = response.body?.getReader();
        if (!reader) {
          throw new Error("无法读取响应流");
        }
  
        const decoder = new TextDecoder("utf-8");
        let buffer = "";
        
        // 用于逐字输出的状态
        let currentContent = "";
        let isThinking = false;
        let isAnswer = false;
        let lastProcessedIndex = 0;
  
        // 处理内容并逐字输出
        const processAndOutput = (content: string) => {
          currentContent += content;
          
          // 逐字输出
          for (let i = lastProcessedIndex; i < currentContent.length; i++) {
            const char = currentContent[i];
            
            // 检查是否开始思考过程
            if (!isThinking && currentContent.substring(i).startsWith("【思考过程】")) {
              onChunkReceived({ content: currentContent.substring(lastProcessedIndex, i) });
              isThinking = true;
              onChunkReceived({ content: "【思考过程】", isThinking: true });
              i += 5; // 跳过标记
              lastProcessedIndex = i;
              continue;
            }
            
            // 检查是否开始最终回答
            if (!isAnswer && currentContent.substring(i).startsWith("【最终回答】")) {
              if (isThinking) {
                onChunkReceived({ 
                  content: currentContent.substring(lastProcessedIndex, i), 
                  isThinking: true 
                });
                isThinking = false;
              } else {
                onChunkReceived({ content: currentContent.substring(lastProcessedIndex, i) });
              }
              
              isAnswer = true;
              onChunkReceived({ content: "【最终回答】", isAnswer: true });
              i += 5; // 跳过标记
              lastProcessedIndex = i;
              continue;
            }
          }
          
          // 输出剩余内容
          const remaining = currentContent.substring(lastProcessedIndex);
          if (remaining) {
            if (isThinking) {
              onChunkReceived({ content: remaining, isThinking: true });
            } else if (isAnswer) {
              onChunkReceived({ content: remaining, isAnswer: true });
            } else {
              onChunkReceived({ content: remaining });
            }
            lastProcessedIndex = currentContent.length;
          }
        };
  
        // 读取流
        while (true) {
          const { value, done } = await reader.read();
          if (done) {
            // 确保所有内容都已输出
            if (lastProcessedIndex < currentContent.length) {
              const remaining = currentContent.substring(lastProcessedIndex);
              if (isThinking) {
                onChunkReceived({ content: remaining, isThinking: true });
              } else if (isAnswer) {
                onChunkReceived({ content: remaining, isAnswer: true });
              } else {
                onChunkReceived({ content: remaining });
              }
            }
            
            onChunkReceived({ finished: true });
            break;
          }
  
          const chunk = decoder.decode(value, { stream: true });
          processAndOutput(chunk);
        }
      } catch (error: any) {
        console.error("API Error:", error);
        onChunkReceived({
          error: `连接错误: ${error.message}`,
          content: "服务暂时不可用",
          isAnswer: true,
        });
      }
    };
  
    return { sendMessage };
  };